package service

import (
	"context"
	"fmt"
	"time"

	"wxpay/pkg/mcontext"

	"wxpay/internal/conf"

	"wxpay/pkg/alipay"

	"wxpay/internal/dao"

	mchApi "wxpay/pkg/wechat_api"
)

const WxUrlHost = "https://api.mch.weixin.qq.com"

type mchService struct {
	d dao.DataStore
}

func NewMchService(d dao.DataStore) *mchService {
	return &mchService{d: d}
}

func (s *mchService) BuildMchApiClient(ctx context.Context, mchID string) (client mchApi.MerchantApiClient, err error) {
	log := mcontext.Logger(ctx)
	log.Info("BuildMchApiClient-start")
	defer func() {
		if r := recover(); r != nil {
			log.Info(fmt.Sprintf("BuildMchApiClient-recovery %v", r))
		}
	}()

	mch, err := s.d.MchConfig().GetMchConfig(ctx, mchID)
	if err != nil {
		log.Info(fmt.Sprintf("BuildMchApiClient-GetMchConfig %s", err.Error()))
		return
	}
	log.Info(fmt.Sprintf("BuildMchApiClient-GetMchConfig %v", mch))
	certs, err := s.d.MchConfig().GetPlatformCert(ctx, mchID)
	if err != nil {
		log.Info(fmt.Sprintf("BuildMchApiClient-GetPlatformCert %s", err.Error()))
		return
	}
	cert, err := s.d.MchConfig().GetLatestPlatformCert(ctx, mchID)
	if err != nil {
		log.Info(fmt.Sprintf("BuildMchApiClient-GetLatestPlatformCert %s", err.Error()))
		return
	}
	log.Info("BuildMchApiClient-ok")
	return mchApi.NewMerchantApiClient(mchID, mch.SerialNo, mch.APICert, WxUrlHost, 60*time.Second, certs, cert.SerialNo, mch.APISecret), nil
}

func (s *mchService) BuildAlipayAgentClient(ctx context.Context, appId string) (*alipay.AlipayClient, error) {
	if appId == "" {
		appId = conf.Conf.Alipay.AppID
	}
	agent, err := s.d.AlipayAgent().GetAgentByAppId(ctx, appId)
	if err != nil {
		return nil, err
	}
	return alipay.NewAliPayClient(agent.AppID, agent.AppKey, agent.PlatKey), nil
}
